<template>
	<view class="draft-list-page">
		<!-- 顶部导航 -->
		<view class="navbar" :style="{paddingTop:safeArea+'px'}">
			<uni-icons type="left" @click="goback"></uni-icons>
			<text class="title">商品管理</text>
			<view class="nav-right">
				<button class="edit-btn" @click="batchOperate">
					{{ isEditing ? '完成' : '编辑' }}
				</button>
				<button class="edit-btn" v-if="isEditing && selectedCount > 0"  @click="deleteSelected">
					<uni-icons type="trash-filled" ></uni-icons>
				</button>
				<button v-if="isEditing && selectedCount > 0" class="batch-put-btn" @click="doBatchPublish">批量申请上架</button>
			</view>
		</view>
        <view class="content">
			<view class="filter-bar">
				<view class="search-box">
					<uni-icons type="search" size="18" color="#999"></uni-icons>
					<input type="text" placeholder="搜索商品名称" v-model="searchKey" @input="handleSearch" />
				</view>
				<picker v-if="categoryList.length > 0" mode="selector" :range="categoryList" @change="handleCategoryChange" class="category-picker">
					<view class="picker-text">
						{{ currentCategory || '全部分类' }}
						<uni-icons type="down" size="16" color="#999"></uni-icons>
					</view>
				</picker>
			</view>
			
			<!-- 草稿列表 -->
			<view class="draft-list">
				<view class="draft-item" v-for="(item, index) in filteredDrafts" :key="item.draftId">
				
					<!-- 选择框（编辑模式） -->
					<view class="item-box">
						<view class="checkbox" v-if="isEditing" @click.stop="handleCheck(item)">
							<uni-icons type="checkbox" :color="item.checked ? '#007aff' : '#ccc'" size="20"></uni-icons>
						</view>
			
						<!-- 商品图片 + 信息容器 -->
						<view class="item-main">
							<view class="item-img">
							
								<image :src="item.images.length > 0 ? item.images[0].url : '/static/images/default-goods.png'" mode="aspectFill"></image>
							</view>
			
							<view class="item-info">
								<view class="info-row">
									<text class="product-name">{{ item.productName || '未命名商品' }}</text>
									<uni-icons v-if="item.source === 'draft'" type="compose" size="20" color="#007aff"></uni-icons>
									<uni-icons v-else-if="item.source === 'goods'" type="cart" size="20" color="#00aa00"></uni-icons>
									
									<!-- 多状态标签 -->
									<view class="status-tags">
										<text class="tag" :class="getStatusClass(item.goodsStatus)">
											{{ item.statusText }}
										</text>
										<text class="tag outstock-tag" v-if="item.isOutOfStock">无库存</text>
										<text class="tag expire-tag" v-if="item.isExpired">已过期</text>
									</view>
								</view>
			
								<view class="info-row date-row">
									<text class="date-label">有效日期：</text>
									<text class="date-text">
										{{ item.startDate || '未设置' }}
										<text v-if="item.startDate && item.endDate">至</text>
										{{ item.endDate || (item.startDate ? '未设置' : '') }}
									</text>
								</view>
			
								<view class="info-row">
									<text class="category-tag">
										{{ getCategoryName(item.categorize) }}
										<text v-if="item.categorize && item.subCategorize">/{{ getSubCategoryName(item.categorize, item.subCategorize) }}</text>
									</text>
									<text class="price">
										¥{{ item.price.toFixed(2) || '0.00' }}
										<text v-if="item.originalPrice" class="original-price">¥{{ item.originalPrice.toFixed(2) }}</text>
									</text>
								</view>
			
								<view class="info-row">
									<text class="stock">库存: {{ item.stock || 0 }} {{ item.unit || '个' }}</text>
								</view>
							</view>
						</view>
					</view>
			
					<!-- 操作按钮 -->
					<view class="item-actions" v-if="isEditing">
						<button class="action-btn edit" @click="navigateToEdit(item)">编辑</button>
						<!-- 仅草稿来源显示删除按钮 -->
						<button class="action-btn dele" @click="confirmDelete(item._id, item.draftId)" v-if="item.source === 'draft'">删除</button>
						<!-- 申请上架/审核/下架按钮（逻辑不变） -->
						<button class="action-btn apply" v-if="['draft', 'offline'].includes(item.goodsStatus)" @click="confirmSinglePublish(item)">申请上架</button>
						<button class="action-btn audit" v-if="isAdmin&&item.goodsStatus === 'pending'" @click="auditGoods(item)">审核上架</button>
						<button class="action-btn offline" v-if="item.goodsStatus === 'online'" @click="confirmOffline(item)">下架</button>
					</view>
				</view>
			</view>
			
			<!-- 空状态/加载中 -->
			<view class="empty-state" v-if="filteredDrafts.length === 0 && !isLoading">
				<uni-icons type="copy" size="60" color="#ccc"></uni-icons>
				<text class="empty-text">{{ emptyText }}</text>
				<button class="add-btn" @click="navigateToAdd">+ 新建商品</button>
			</view>
			
			<view class="loading-state" v-if="isLoading">
				<uni-icons type="spinner" size="40" color="#007aff" animation="spin"></uni-icons>
				<text class="loading-text">加载中...</text>
			</view>
			
		</view>
		<!-- 筛选栏 -->
		

		<!-- 批量申请上架弹窗 -->
		<uni-popup ref="batchPublishPopup" type="dialog">
			<uni-popup-dialog
				:content="`确定将选中的${selectedCount}条草稿申请上架？`"
				confirmText="确认"
				cancelText="取消"
				mode="base"
				:before-close="true"
				@confirm="doBatchPublish"
				@close="cancelBatchPublish"
			></uni-popup-dialog>
		</uni-popup>

		<!-- 单个申请上架弹窗 -->
		<uni-popup ref="singlePublishPopup" type="dialog">
			<uni-popup-dialog
				content="确定申请上架该商品？提交后将进入审核流程"
				title="申请上架"
				cancelText="取消"
				confirmText="确认"
				:before-close="true"
				@confirm="doSinglePublish"
				@close="cancelSinglePublish"
			></uni-popup-dialog>
		</uni-popup>

		<!-- 下架确认弹窗 -->
		<uni-popup ref="offlinePopup" type="dialog">
			<uni-popup-dialog
				content="确定下架该商品？下架后将不再展示"
				title="确认下架"
				cancelText="取消"
				confirmText="确认"
				:before-close="true"
				@confirm="doOffline"
				@close="cancelOffline"
			></uni-popup-dialog>
		</uni-popup>

		<!-- 固定新增按钮 -->
		<view class="fixed-add-btn" @click="navigateToAdd">
			<uni-icons type="plusempty" size="28" color="#fff"></uni-icons>
			<text style="font-size: 22rpx;">新增商品</text>
		</view>
	</view>
</template>

<script>
const db = uniCloud.database();
const _ = db.command;

export default {
	data() {
		return {
			draftList: [], // 草稿列表（含关联的正式商品信息）
			filteredDrafts: [], // 筛选后列表
			searchKey: '', // 搜索关键词
			currentCategory: '', // 当前选中分类
			categoryList: ['全部分类'], // 分类下拉选项
			isEditing: false, // 编辑模式
			publishItem: null, // 待申请上架的单个草稿
			offlineItem: null, // 待下架的商品
			allCategories: [], // 完整分类数据
			categoryMap: {}, // 一级分类ID→名称映射
			subCategoryMap: {}, // 二级分类{一级ID_二级ID}→名称映射
			isLoading: true, // 加载中状态
			emptyText: '暂无商品草稿', // 空状态文本
			isAdmin:true,// 是否为管理员（实际项目从用户信息获取）
			safeArea:0
		};
	},

	computed: {
		// 选中的草稿数量
		selectedCount() {
			return this.filteredDrafts.filter((item) => item.checked).length;
		},
		storeData() {
			return this.$store.state.msg || {};
		},
		systemInfo(){
			return this.$store.state.msg.systemInfo
		}
	},
    watch:{
		isAdmin:{
			handler(newval){
		        console.log("是否管理员",newval);		
			},immediate:true
		}
	},
	onLoad() {
		this.safeArea=this.systemInfo.safeArea.top
		// 初始化：获取分类→加载草稿→判断管理员权限
		this.getCategoryFromCloud()
			.then(() => this.loadOnlineDrafts())
			.then(() => this.checkAdminPermission())
			.catch((error) => {
				this.isLoading = false;
				this.emptyText = '数据加载失败，请重试';
				console.error('初始化失败:', error);
			});
	},
	

	methods: {
		// 检查是否为管理员（示例：实际从用户角色判断）
		async checkAdminPermission() {
			// 实际项目中从用户信息表获取角色（如：this.storeData.user?.role === 'admin'）
			// this.isAdmin = this.storeData.user?.userId === 'admin'; // 示例逻辑
		},
       goback(){
		   uni.navigateBack()
	   },
		// 加载草稿（关联sendgood表，获取最新状态）
		async loadOnlineDrafts() {
			try {
				this.isLoading = true;
				const userId = this.storeData.user?.userId;
				if (!userId) throw new Error('未获取到用户信息');

				// 1. 查询草稿表和正式商品表（逻辑不变）
				const draftQuery = await db.collection('productDraft').where({ senderUserId: userId }).orderBy('updateTime', 'desc').get();
				const drafts = draftQuery.data || draftQuery.result?.data || [];
				const goodsQuery = await db.collection('sendgood').where({ senderUserId: userId }).orderBy('sendTime', 'desc').get();
				const allGoods = goodsQuery.data || goodsQuery.result?.data || [];

				// 2. 构建草稿映射表（逻辑不变）
				const draftMap = new Map();
				drafts.forEach((draft) => {
					if (draft.relatedGoodsId) draftMap.set(draft.relatedGoodsId, draft);
				});

				// 3. 合并数据：关键添加 source 字段
				const mergedList = [];

				// 3.1 处理正式商品（添加 source 标识）
				allGoods.forEach((goods) => {
					const relatedDraft = draftMap.get(goods._id);
					if (relatedDraft) {
						// 有对应草稿的正式商品：来源为 draft（编辑加载草稿）
						mergedList.push({
							...relatedDraft,
							goodsStatus: goods.status,
							statusText: this.getStatusText(goods.status),
							isOutOfStock: (relatedDraft.stock || 0) <= 0,
							isExpired: this.isDraftExpired(relatedDraft),
							checked: false,
							source: 'draft', // 来源：草稿表
							goodsId: goods._id // 额外保存正式商品ID（可选）
						});
						draftMap.delete(goods._id);
					} else {
						// 无对应草稿的正式商品：来源为 goods（编辑加载正式商品）
						mergedList.push({
							...goods,
							draftId: `goods_${goods._id}`, // 临时draftId（避免模板报错）
							isPublished: true,
							goodsStatus: goods.status,
							statusText: this.getStatusText(goods.status),
							isOutOfStock: (goods.stock || 0) <= 0,
							isExpired: this.isDraftExpired(goods),
							checked: false,
							source: 'goods', // 来源：正式商品表
							goodsId: goods._id // 正式商品ID（编辑页需用）
						});
					}
				});

				// 3.2 处理剩余纯草稿（添加 source 标识）
				draftMap.forEach((draft) => {
					mergedList.push({
						...draft,
						goodsStatus: 'draft',
						statusText: this.getStatusText('draft'),
						isOutOfStock: (draft.stock || 0) <= 0,
						isExpired: this.isDraftExpired(draft),
						checked: false,
						source: 'draft' // 来源：草稿表
					});
				});

				// 4. 排序和赋值（逻辑不变）
				mergedList.sort((a, b) => {
					const timeA = a.updateTime || a.sendTime || 0;
					const timeB = b.updateTime || b.sendTime || 0;
					return timeB - timeA;
				});
				this.draftList = mergedList;
				this.filteredDrafts = [...mergedList];
				this.emptyText = mergedList.length === 0 ? '暂无草稿或商品' : '暂无匹配的内容';
			} catch (error) {
				console.error('加载失败:', error);
				this.emptyText = '加载失败，请重试';
				this.draftList = [];
				this.filteredDrafts = [];
			} finally {
				this.isLoading = false;
			}
		},
		// 判断草稿是否过期
		isDraftExpired(item) {
			if (!item.endDate) return false;
			const now = new Date().getTime();
			const endTime = new Date(item.endDate).getTime();
			return now > endTime;
		},

		// 状态文本映射（状态值→显示文本）
		getStatusText(status) {
			const statusMap = {
				draft: '草稿',
				apply: '申请上架',
				pending: '待审核',
				online: '审核上架',
				offline: '已下架'
			};
			return statusMap[status] || '未知状态';
		},

		// 状态样式映射（状态值→CSS类名）
		getStatusClass(status) {
			const classMap = {
				draft: 'draft-tag',
				apply: 'apply-tag',
				pending: 'pending-tag',
				online: 'online-tag',
				offline: 'offline-tag'
			};
			return classMap[status] || 'draft-tag';
		},

		// 编辑模式选择框
		handleCheck(item) {
			item.checked = !item.checked;
		},

		// 跳转编辑页
		// 跳转编辑页（核心修改）
		navigateToEdit(item) {
			// 1. 根据来源确定参数：source + 对应ID
			const { source, draftId, goodsId } = item;
			let jumpParams = '';

			if (source === 'draft') {
				// 来源为草稿：传递 draftId
				if (!draftId) return uni.showToast({ title: '草稿信息有误', icon: 'none' });
				jumpParams = `source=draft&id=${draftId}`;
			} else if (source === 'goods') {
				// 来源为正式商品：传递 goodsId（sendgood表的ID）
				if (!goodsId) return uni.showToast({ title: '商品信息有误', icon: 'none' });
				jumpParams = `source=goods&id=${goodsId}`;
			} else {
				return uni.showToast({ title: '数据来源异常', icon: 'none' });
			}

			// 2. 跳转编辑页
			uni.navigateTo({
				url: `/pages/createGood/createGood?${jumpParams}`,
				fail: (err) => {
					console.error('编辑页跳转失败:', err);
					uni.showToast({ title: '跳转失败，请重试', icon: 'none' });
				}
			});
		},

		// 单个申请上架确认
		confirmSinglePublish(item) {
			this.publishItem = item;
			this.$refs.singlePublishPopup.open();
		},

		// 执行单个申请上架
		async doSinglePublish() {
			if (!this.publishItem) return;

			// 验证草稿完整性
			const validateRes = this.validateDraftBeforePublish(this.publishItem);
			if (!validateRes.valid) {
				uni.showToast({ title: validateRes.msg, icon: 'none' });
				this.$refs.singlePublishPopup.close();
				return;
			}

			try {
				const now = new Date().getTime();
				const draftId = this.publishItem.draftId;

				if (this.publishItem.relatedGoodsId) {
					// 已有关联商品：更新状态为待审核
					await db.collection('sendgood').doc(this.publishItem.relatedGoodsId).update({
						status: 'pending',
						updateTime: now
					});
				} else {
					// 无关联商品：新增正式商品（状态待审核）
					const goodsData = {
						productName: this.publishItem.productName,
						categorize: this.publishItem.categorize,
						subCategorize: this.publishItem.subCategorize,
						specs: this.publishItem.specs,
						unit: this.publishItem.unit,
						price: this.publishItem.price,
						originalPrice: this.publishItem.originalPrice,
						stock: this.publishItem.stock,
						description: this.publishItem.description,
						tag: this.publishItem.tag,
						barcode: this.publishItem.barcode,
						images: this.publishItem.images,
						startDate: this.publishItem.startDate,
						endDate: this.publishItem.endDate,
						location: this.publishItem.location,
						senderUserId: this.storeData.user?.userId,
						sendTime: now,
						status: 'pending', // 新增商品默认待审核
						saled: 0
					};
					const addRes = await db.collection('sendgood').add(goodsData);
					// 关联新商品ID到草稿
					await db.collection('productDraft').where({ draftId }).update({ relatedGoodsId: addRes.result.id });
				}

				// 更新草稿状态为申请上架
				await db.collection('productDraft').where({ draftId }).update({
					status: 'apply',
					updateTime: now
				});

				// 刷新列表
				await this.loadOnlineDrafts();
				uni.showToast({ title: '申请上架成功，待审核' });
			} catch (error) {
				console.error('申请上架失败:', error);
				uni.showToast({ title: '申请失败，请重试', icon: 'none' });
			} finally {
				this.publishItem = null;
				this.$refs.singlePublishPopup.close();
			}
		},

		// 审核上架（管理员操作）
		async auditGoods(item) {
			if (!item.relatedGoodsId) {
				return uni.showToast({ title: '商品信息不完整', icon: 'none' });
			}

			try {
				const now = new Date().getTime();
				// 更新正式商品状态为已上架
				await db.collection('sendgood').doc(item.relatedGoodsId).update({
					status: 'online',
					auditTime: now
				});
				// 同步更新草稿状态
				await db.collection('productDraft').where({ draftId: item.draftId }).update({
					status: 'online',
					updateTime: now
				});

				await this.loadOnlineDrafts();
				uni.showToast({ title: '审核通过，商品已上架' });
			} catch (error) {
				console.error('审核失败:', error);
				uni.showToast({ title: '审核失败，请重试', icon: 'none' });
			}
		},

		// 下架确认
		confirmOffline(item) {
			this.offlineItem = item;
			this.$refs.offlinePopup.open();
		},

		// 执行下架
		async doOffline() {
			console.log('44444', this.offlineItem);
			if (!this.offlineItem?.relatedGoodsId) {
				uni.showToast({ title: '商品信息有误', icon: 'none' });
				this.$refs.offlinePopup.close();
				return;
			}

			try {
				const now = new Date().getTime();
				// 更新正式商品状态为已下架
				await db.collection('sendgood').doc(this.offlineItem.relatedGoodsId).update({
					status: 'offline',
					offlineTime: now
				});
				// 同步更新草稿状态
				await db.collection('productDraft').where({ draftId: this.offlineItem.draftId }).update({
					status: 'offline',
					updateTime: now
				});

				await this.loadOnlineDrafts();
				uni.showToast({ title: '商品已下架' });
			} catch (error) {
				console.error('下架失败:', error);
				uni.showToast({ title: '下架失败，请重试', icon: 'none' });
			} finally {
				this.offlineItem = null;
				this.$refs.offlinePopup.close();
			}
		},

		// 批量操作（编辑/完成）
		batchOperate() {
			if (!this.isEditing) {
				// 进入编辑模式：重置选中状态
				this.filteredDrafts.forEach((item) => (item.checked = false));
				this.isEditing = true;
				return;
			}

			// 退出编辑模式：处理删除
		 else {
				this.isEditing = false;
			}
		},

		// 批量申请上架
		async doBatchPublish() {
			const selectedDrafts = this.filteredDrafts.filter((item) => item.checked);
			if (selectedDrafts.length === 0) return;

			// 验证选中的草稿
			const { validDrafts, invalidMsg } = this.batchValidateDrafts(selectedDrafts);
			if (invalidMsg) {
				uni.showModal({ title: '提示', content: invalidMsg, showCancel: false });
				if (validDrafts.length === 0) {
					this.$refs.batchPublishPopup.close();
					return;
				}
			}

			try {
				const now = new Date().getTime();
				// 批量处理每个草稿
				for (const draft of validDrafts) {
					if (draft.relatedGoodsId) {
						// 已有关联商品：更新为待审核
						await db.collection('sendgood').doc(draft.relatedGoodsId).update({ status: 'pending', updateTime: now });
					} else {
						// 无关联商品：新增正式商品
						const goodsData = {
							// 商品基础字段（同单个申请上架，略）
							productName: draft.productName,
							categorize: draft.categorize,
							unit: draft.unit,
							price: draft.price,
							stock: draft.stock,
							description: draft.description,
							images: draft.images,
							senderUserId: this.storeData.user?.userId,
							sendTime: now,
							status: 'pending',
							saled: 0
						};
						const addRes = await db.collection('sendgood').add(goodsData);
						// 关联新商品ID
						await db.collection('productDraft').where({ draftId: draft.draftId }).update({ relatedGoodsId: addRes.id });
					}
					// 更新草稿状态
					await db.collection('productDraft').where({ draftId: draft.draftId }).update({ status: 'apply', updateTime: now });
				}

				await this.loadOnlineDrafts();
				uni.showToast({
					title: `成功申请${validDrafts.length}条，${selectedDrafts.length - validDrafts.length}条无效`,
					icon: 'none'
				});
			} catch (error) {
				console.error('批量申请失败:', error);
				uni.showToast({ title: '批量申请失败，请重试', icon: 'none' });
			} finally {
				this.$refs.batchPublishPopup.close();
				this.isEditing = false;
			}
		},

		// 取消批量申请
		cancelBatchPublish() {
			this.$refs.batchPublishPopup.close();
		},

		// 取消单个申请
		cancelSinglePublish() {
			this.publishItem = null;
			this.$refs.singlePublishPopup.close();
		},

		// 取消下架
		cancelOffline() {
			this.offlineItem = null;
			this.$refs.offlinePopup.close();
		},

		// 草稿上架前验证
		validateDraftBeforePublish(draft) {
			if (!draft.productName || !draft.categorize || !draft.unit || !draft.price || !draft.description || !draft.images?.length) {
				return { valid: false, msg: '信息不完整，无法申请上架' };
			}
			if (this.isDraftExpired(draft)) {
				return { valid: false, msg: '商品已过期，无法申请上架' };
			}
			return { valid: true };
		},

		// 批量验证草稿
		batchValidateDrafts(drafts) {
			let invalidCount = 0;
			const validDrafts = [];
			drafts.forEach((draft) => {
				const { valid } = this.validateDraftBeforePublish(draft);
				if (valid) validDrafts.push(draft);
				else invalidCount++;
			});
			const invalidMsg = invalidCount > 0 ? `${invalidCount}条草稿信息不完整或已过期` : '';
			return { validDrafts, invalidMsg };
		},

		// 获取分类数据
		async getCategoryFromCloud() {
			try {
				const userId = this.storeData.user?.userId;
				if (!userId) throw new Error('未获取到用户信息');

				let res = await db.collection('category').where({ userId }).get();
				if (res.result.data.length === 0) {
					// 复制默认分类
					const defaultRes = await db.collection('category').where({ userId: 'system' }).get();
					if (defaultRes.result.data.length === 0) throw new Error('默认分类不存在');

					await db.collection('category').add({
						userId,
						category: defaultRes.result.data[0].category
					});
					res = await db.collection('category').where({ userId }).get();
				}

				const categoryData = res.result.data[0]?.category || [];
				this.allCategories = categoryData;
				// 构建分类映射
				categoryData.forEach((cate) => {
					this.categoryMap[cate.id] = cate.name;
					cate.subCategory?.forEach((sub) => {
						this.subCategoryMap[`${cate.id}_${sub.id}`] = sub.name;
					});
				});
				// 分类下拉选项
				this.categoryList = ['全部分类', ...categoryData.map((cate) => cate.name)];
			} catch (error) {
				throw error;
			}
		},

		// 搜索筛选
		handleSearch() {
			const keyword = this.searchKey.toLowerCase();
			this.filteredDrafts = keyword ? this.draftList.filter((item) => item.productName?.toLowerCase().includes(keyword)) : [...this.draftList];
			this.emptyText = this.filteredDrafts.length === 0 ? '暂无匹配的草稿' : '暂无商品草稿';
		},

		// 分类筛选
		handleCategoryChange(e) {
			const index = e.detail.value;
			this.currentCategory = this.categoryList[index];
			if (index === 0) {
				this.filteredDrafts = [...this.draftList];
			} else {
				const categoryId = Object.keys(this.categoryMap).find((key) => this.categoryMap[key] === this.currentCategory);
				this.filteredDrafts = this.draftList.filter((item) => item.categorize === categoryId);
			}
			this.emptyText = this.filteredDrafts.length === 0 ? '暂无匹配的草稿' : '暂无商品草稿';
		},

		// 获取分类名称
		getCategoryName(cateId) {
			return this.categoryMap[cateId] || '未知分类';
		},

		// 获取子分类名称
		getSubCategoryName(cateId, subCateId) {
			return this.subCategoryMap[`${cateId}_${subCateId}`] || '未知子分类';
		},

		// 确认删除
		confirmDelete(_id, draftId) {
			uni.showModal({
				title: '确认删除',
				content: '确定删除该草稿？',
				confirmText: '删除',
				confirmColor: '#ff3d00',
				success: (res) => res.confirm && this.doDelete(draftId)
			});
		},

		// 执行单个删除
		async doDelete(draftId) {
			try {
				// 删除云端草稿
				await db.collection('productDraft').where({ draftId }).remove();
				// 过滤本地列表
				const newDrafts = this.draftList.filter((item) => item.draftId !== draftId);
				this.updateDrafts(newDrafts);
				uni.showToast({ title: '删除成功' });
			} catch (error) {
				console.error('删除失败:', error);
				uni.showToast({ title: '删除失败，请重试', icon: 'none' });
			}
		},

		// 批量删除
		// 批量删除（仅删草稿来源的项）
		async deleteSelected() {
		
			const res=	uni.showModal({
					title: '批量删除',
					content: `确定删除选中的${this.selectedCount}条草稿？`,
					confirmText: '删除',
					confirmColor: '#ff3d00',
				
				});
			if(!res.confirm) return
			// 筛选出来源为 draft 且被选中的项
			const selectedDrafts = this.filteredDrafts.filter((item) => item.checked && item.source === 'draft');
			const selectedIds = selectedDrafts.map((item) => item.draftId);

			if (selectedIds.length === 0) return;

			try {
				await db
					.collection('productDraft')
					.where({ draftId: _.in(selectedIds) })
					.remove();
				const newDrafts = this.draftList.filter((item) => !selectedIds.includes(item.draftId));
				this.updateDrafts(newDrafts);
				uni.showToast({ title: `删除成功${selectedIds.length}条` });
			} catch (error) {
				console.error('批量删除失败:', error);
				uni.showToast({ title: '删除失败，请重试', icon: 'none' });
			}finally{
				this.isEditing=false
			}
		},

		// 更新本地列表
		updateDrafts(newDrafts) {
			this.draftList = newDrafts;
			this.filteredDrafts = [...newDrafts];
			this.emptyText = newDrafts.length === 0 ? '暂无商品草稿' : '暂无匹配的草稿';
		},

		// 跳转新增商品页
		navigateToAdd() {
			uni.navigateTo({ url: '/pages/createGood/createGood' });
		}
	}
};
</script>

<style lang="scss" scoped>
.draft-list-page {
	min-height: 100vh;
	background-color: #f5f5f5;
}

/* 导航栏 */
.navbar {
	display: flex;
	position: fixed;
	background-color: #fff;
	top: 0;
	left: 0;
	right: 0;
	z-index: 9999;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx 30rpx 15rpx 15rpx;
	background-color: #fff;
	border-bottom: 1px solid #eee;
}

.title {
	font-size: 36rpx;
	font-weight: 500;
	color: #333;
}

.nav-right {
	display: flex;
	gap: 20rpx;
}

.edit-btn {
	font-size: 32rpx;
	color: #007aff;
	background: transparent;
	padding: 10rpx 24rpx;
	line-height: normal;
	border-radius: 8rpx;
}

.batch-put-btn {
	font-size: 30rpx;
	color: #fff;
	background-color: #ff3d00;
	padding: 10rpx 24rpx;
	height: auto;
	line-height: normal;
	border-radius: 8rpx;
}
.content{
	margin-top: 120rpx;
}
/* 筛选栏 */
.filter-bar {
	display: flex;
	padding: 16rpx 30rpx;
	background-color: #fff;
	border-bottom: 1px solid #eee;
	align-items: center;
}

.search-box {
	flex: 1;
	display: flex;
	align-items: center;
	background-color: #f5f5f5;
	border-radius: 60rpx;
	padding: 10rpx 20rpx;
	margin-right: 20rpx;
}

.search-box input {
	flex: 1;
	font-size: 28rpx;
	padding: 0 10rpx;
	height: 40rpx;
	line-height: 40rpx;
}

.category-picker {
	width: 200rpx;
	background-color: #f5f5f5;
	border-radius: 60rpx;
	padding: 10rpx 20rpx;
}

.picker-text {
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	color: #333;
}

/* 草稿列表 */
.draft-list {
	padding: 16rpx 30rpx 120rpx;
}

.draft-item {
	display: flex;
	position: relative;
	flex-direction: column;
	padding: 20rpx 30rpx;
	background-color: #fff;
	border-bottom: 1px solid #eee;
	margin-bottom: 16rpx;
	border-radius: 12rpx;
}
.source-tag {
	position: absolute;
	background-color: #fff;
	padding: 2rpx;
	border-radius: 50%;
	top:0;
	left: 0;
	z-index: 999;
}

.checkbox {
	width: 60rpx;
	display: flex;
	justify-content: center;

	align-items: center;
	padding-top: 10rpx;
	margin-right: 10rpx;
}
.item-box {
	display: flex;
}
.item-main {
	display: flex;
	align-items: flex-start;
	margin-bottom: 16rpx;
}

.item-img {
	width: 140rpx;
	height: 140rpx;
	
	border-radius: 10rpx;
	overflow: hidden;
	margin-right: 20rpx;
	flex-shrink: 0;
}

.item-img image {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

.item-info {
	flex: 1;
}

.info-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 8rpx;
}

.info-row:last-child {
	margin-bottom: 0;
}

.product-name {
	font-size: 32rpx;
	color: #333;
	max-width: 400rpx;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.status-tags {
	display: flex;
	gap: 8rpx;
}

.tag {
	font-size: 22rpx;
	padding: 2rpx 8rpx;
	border-radius: 4rpx;
}

/* 多状态标签样式 */
.draft-tag {
	color: #999;
	background-color: #f5f5f5;
}
.apply-tag {
	color: #007aff;
	background-color: #e8f3ff;
}
.pending-tag {
	color: #ff9500;
	background-color: #fff8e6;
}
.online-tag {
	color: #00cc66;
	background-color: #e6ffef;
}
.offline-tag {
	color: #ff3d00;
	background-color: #fee;
}

.outstock-tag {
	color: #ff9500;
	background-color: #fff8e6;
}

.expire-tag {
	color: #ff3d00;
	background-color: #fee;
}

.date-row {
	align-items: flex-start;
	margin: 8rpx 0;
}

.date-label {
	font-size: 24rpx;
	color: #666;
	margin-right: 8rpx;
}

.date-text {
	font-size: 24rpx;
	color: #333;
	flex: 1;
}

.category-tag {
	font-size: 26rpx;
	color: #666;
	background-color: #f0f7ff;
	padding: 4rpx 12rpx;
	border-radius: 40rpx;
}

.price {
	font-size: 30rpx;
	color: #f53f3f;
	font-weight: bold;
}

.original-price {
	font-size: 24rpx;
	color: #999;
	text-decoration: line-through;
	margin-left: 10rpx;
	font-weight: normal;
}

.stock {
	font-size: 26rpx;
	color: #666;
}

/* 操作按钮 */
.item-actions {
	display: flex;
	flex-direction: row;
	gap: 12rpx;
	padding-top: 16rpx;
	border-top: 1px dashed #f5f5f5;
}

.action-btn {
	flex: 1;
	text-align: center;
	padding: 12rpx 0;
	font-size: 26rpx;
	border-radius: 8rpx;
	line-height: normal;
	height: auto;
}

.edit {
	color: #007aff;
	background-color: #f0f7ff;
}
.dele {
	color: #ff3d00;
	background-color: #fee;
}
.apply {
	color: #ff9500;
	background-color: #fff8e6;
}
.audit {
	color: #00cc66;
	background-color: #e6ffef;
}
.offline {
	color: #999;
	background-color: #f5f5f5;
}

/* 空状态/加载中 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding-top: 200rpx;
}

.empty-text {
	font-size: 30rpx;
	color: #999;
	margin: 30rpx 0;
}

.add-btn {
	background-color: #007aff;
	color: #fff;
	padding: 15rpx 40rpx;
	border-radius: 60rpx;
	font-size: 30rpx;
	margin-top: 20rpx;
}

.loading-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding-top: 200rpx;
}

.loading-text {
	font-size: 28rpx;
	color: #666;
	margin-top: 20rpx;
}

/* 固定新增按钮 */
.fixed-add-btn {
	position: fixed;
	bottom: 100rpx;
	right: 30rpx;
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	background-color: #007aff;
	color: #fff;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.2);
	z-index: 999;
}
</style>
